package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RPC server
 * 1. 接收请求
 * 2. 发送发送响应
 */
public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        // 2.开启信道
        Channel channel = connection.createChannel();
        // 3. 接收请求
        channel.basicQos(1);
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body);
                System.out.println("接收到请求：" + request);
                // 针对服务器构造响应内容进行响应
                String response = "针对请求" + request +", 响应成功.";
                AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",Constants.RPC_RESPONSE_QUEUE,props,response.getBytes());
                // 手动确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);
    }
}
